<template>
	<div class="common-layout">
	    <el-container>
			<el-header><Header></Header></el-header>
			<el-main>
				<div class="top">
					<h3>商品分类</h3>
					<!-- <el-button type="primary">添加商品分类</el-button> -->
					<el-button plain type="primary" v-if="counter.btnsObj.addFlag" @click="addClass">{{counter.btnsObj.addName}}</el-button>
				</div>
				<el-table
					:data="tableData"
					style="width: 100%"
					height="60vh"
				>
					<el-table-column 
						type="expand"
					>
						<template #default="scope">
							<el-table :data="scope.row.children" >
								<el-table-column align="center" prop="separateName" width="230"></el-table-column>
								<el-table-column align="center">
									<template #default = "image">
										<img :src="downloadUrl+image.row.separateImage" style=" width:80px;height: 80px;object-fit: cover;">
									</template>
								</el-table-column>
								<el-table-column align="center" prop="separateStatus"></el-table-column>
								
								<el-table-column align="center">
									  <template #default="busy">
										 <span plain @click="edit(busy.row)" class="mya" style="cursor: pointer;">编辑</span>
										 <span class="mya" @click="del(busy.row)" style="cursor: pointer;">删除</span>
									  </template>
								</el-table-column>
							</el-table>
						</template>
					</el-table-column>
				    <el-table-column
						prop="separateName" 
						label="分类名称"
					/>
				      <el-table-column label="分类图片">
						<template #default = "image">
							<img :src="downloadUrl+image.row.separateImage" style=" width:80px;height: 80px;object-fit: cover;">
						</template>
					  </el-table-column>
				      <el-table-column prop="separateStatus" label="是否显示" />
					  <el-table-column>
						  <template #default="busy">
							 <span plain @click="edit(busy.row)" class="mya" style="cursor: pointer;">编辑</span>
							 <span class="mya" @click="del(busy.row)" style="cursor: pointer;">删除</span>
						  </template>
					  </el-table-column>
				    </el-table>
				
				<el-pagination
					layout="prev,pager,next"
					:page-count="total"
					:page-size="pageSize"
					v-model:current-page="pageIndex"	
					@current-change="changePage"
				></el-pagination>
			</el-main>
	    </el-container>
	</div>
	<!-- 编辑商品分类 -->
	 <el-dialog v-model="dialogFormVisible" title="编辑商品分类" width="500">
	    <el-form :model="form">
	      <el-form-item label="分类名称" >
	        <el-input v-model="form.separateName" autocomplete="off" />
	      </el-form-item>
	      <el-form-item label="上级分类" >
	        <el-select v-model="form.separateSuperior" placeholder="" style="width: 200px;">
	          <el-option 
	      			  v-for="item in obj"
	      			  :label="item.separateName" 
	      			  :value="item.separateId" />
	        </el-select>
	      </el-form-item>
		  <el-form-item label="分类图片">
			   <el-upload
			      class="avatar-uploader"
			      :action="uploadUrl"
			      :show-file-list="false"
			      :on-success="handleAvatarSuccess"
			      :before-upload="beforeAvatarUpload"
			    >
			      <img v-if="imageUrl" :src="imageUrl" class="avatarimg" />
			      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
			    </el-upload>
		  </el-form-item>
		  <el-form-item label="是否显示">
			   <el-switch v-model="value" />
		  </el-form-item>
	    </el-form>
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="cancel">取消</el-button>
	        <el-button type="primary" @click="sure">
	          确定
	        </el-button>
	      </div>
	    </template>
	  </el-dialog>
	  
	  
	 <!-- 添加商品分类-->
	 <el-dialog v-model="dialogFormVisible1" title="添加商品分类" width="500">
	    <el-form :model="formtwo" ref="ruleFormRef" :rules="rules" label-width="auto">
	      <el-form-item label="分类名称" prop="separateName">
	        <el-input v-model="formtwo.separateName" autocomplete="off" />
	      </el-form-item>
	      <el-form-item label="上级分类" prop="separateSuperior" >
	        <el-select v-model="formtwo.separateSuperior" placeholder="" style="width: 200px;">
	          <el-option 
			  v-for="item in obj"
			  :label="item.separateName"
			  :value="item.separateId" />
	        </el-select>
	      </el-form-item>
	 	<el-form-item label="分类图片" prop="separateImage">
	 		<el-upload
				v-model="formtwo.separateImage"
	 			class="avatar-uploader"
	 			:action="uploadUrl"
	 			:show-file-list="false"
	 			:on-success="handleAvatarSuccess2"
	 			:before-upload="beforeAvatarUpload"
	 		>
	 			<img v-if="imageUrl2" :src="imageUrl2" class="avatarimg" />
	 			<el-icon class="avatar-uploader-icon"><Plus /></el-icon>
			</el-upload>
	 	</el-form-item>
	 		  <el-form-item label="是否显示" prop="separateStatus">
	 			   <el-switch v-model="formtwo.separateStatus" />
	 		  </el-form-item>
	    </el-form>
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="dialogFormVisible1 = false">取消</el-button>
	        <el-button type="primary" @click="save(ruleFormRef)">
	          确定
	        </el-button>
	      </div>
	    </template>
	  </el-dialog>
	  
	  
	  <!-- 删除商品分类 -->
	  <el-dialog
	     v-model="dialogVisible"
	     title="提示"
	     width="500"
	   >
	   <el-icon class="icon"><WarningFilled /></el-icon>
	     <span>确定要删除该数据吗</span>
	     <template #footer>
	       <div class="dialog-footer">
	         <el-button @click="dialogVisible = false">取消</el-button>
	         <el-button type="primary" @click="define">
	           确定
	         </el-button>
	       </div>
	     </template>
	   </el-dialog>
</template>

<script setup>
	import { useRouter,useRoute } from 'vue-router';
	import {useCounterStore} from "../stores/counter"
	let route = useRoute();
	let router = useRouter();
	let counter = useCounterStore();
	counter.btns = route.meta.btns
	import Header from "@/components/Header.vue"
	import {GoodsClassList,CategoryParent,DelGoodsClass,UpdateGoodsClass,InsertGoodsClass} from "@/api"
	import { onMounted, ref,reactive } from 'vue';
	import { uploadUrl,baseUrl,downloadUrl } from "@/utils/request";
	import { Plus,WarningFilled } from '@element-plus/icons-vue'
	import { ElMessage } from 'element-plus'
	const tableData = ref([])
	let pageIndex=ref(1);
	let pageSize=5;
	let total=ref(0)
	//商品分类列表
	const getclassList=async ()=>{
		let res=await GoodsClassList({
			pageIndex:pageIndex.value,
			pageSize:pageSize,
			siteId:1
		})
		// console.log("商品分类",res)
		tableData.value=res.separate
		total.value=res.pageCount
	}
	//图片上传
	const imageUrl = ref('')
	const imageUrl2 = ref('')
	//图片上传成功
	const handleAvatarSuccess= (response,uploadFile) => {
		// console.log('上传成功',response)
	  imageUrl.value = URL.createObjectURL(uploadFile.raw)
	  // console.log(imageUrl.value);
	  form.separateImage=response.data
	}
	//添加中图片上传成功
	const handleAvatarSuccess2= (response,uploadFile) => {
		// console.log('上传成功',response)
	  imageUrl2.value = URL.createObjectURL(uploadFile.raw)
	  // console.log(imageUrl2.value);
	  formtwo.separateImage=response.data

	}
	//图片上传前
	const beforeAvatarUpload= (rawFile) => {
		// console.log(rawFile)
		let reg=/(jpeg|png|jpeg)$/
	  if (!reg.test(rawFile.type)) {
	    ElMessage.error('图片只能是jpg/jpeg/png格式的')
	    return false
	  } else if (rawFile.size / 1024 / 1024 > 4) {
	    ElMessage.error('图片的大小不能超过4MB')
	    return false
	  }
	  return true
	}
	//开关
	const value = ref(true)
	const value1 = ref(false)
	let mySwitch = ref(null);
	//点击编辑
	let dialogFormVisible = ref(false)
	let dialogFormVisible1 = ref(false)
	let imageUrls =ref("")
	let formLabelWidth = '140px'
	let form = reactive({
		separateId:"",
		separateName: '',
		separateSuperior: "",
		separateStatus:"",
		separateImage:"",
	})
	const edit =async (row)=>{
		
		// console.log("row",row)
		
		form = row
		imageUrl.value =  downloadUrl+form.separateImage
		// console.log("form",form)
		dialogFormVisible.value=true;
	}
	//点击编辑中的确定
	const sure =async ()=>{
		dialogFormVisible.value = false
		let rop = await UpdateGoodsClass(form)
		if(rop == "更新成功"){
			ElMessage.success({
				message:"修改成功"
			})
		}else{
			ElMessage.error({
				message:"修改失败"
			})
		}
		// console.log("rop",rop)
		// console.log("bbbb",form)
	}
	
	//添加中的验证
	const ruleFormRef = ref(null)
	const rules = reactive({
		separateName: [
		    { required: true, message: '分类名称不能为空', trigger: 'blur' },
		],
		separateImage: [
		    { required: true, message: '分类图片不能为空', trigger: 'blur' },
		],
		separateStatus: [
		    { required: true, message: '是否显示不能为空', trigger: 'blur' },
		],
		
	})
	
	
	//点击添加
	let formtwo = reactive({
		separateName: '',
		separateImage:"",
		separateSuperior:null,
		separateStatus:false,
		siteId:1
	})
	const addClass =()=>{
		imageUrl2.value=''
		formtwo = reactive({
			separateName: '',
			separateImage: "",
			separateSuperior:null,
			separateStatus:false,
			siteId:1
		})
		dialogFormVisible1.value=true;
		
	}
	
	//点击添加中的确定
	const save=(formEl)=>{
		formEl.validate(async (valid)=>{
			if(valid){
				dialogFormVisible1.value=false;
				let rulAddDate = reactive({
					separateName:formtwo.separateName,
					separateSuperior:formtwo.separateSuperior,
					separateImage:formtwo.separateImage,
					siteId:1,
				})
				if(formtwo.separateStatus == true){
					rulAddDate.separateStatus = "是"
				}else{
					rulAddDate.separateStatus = "否"
				}
				// console.log("点击确定后",rulAddDate)
				//调取添加商品接口
				let res = await InsertGoodsClass(rulAddDate)
				// console.log("添加商品分类",res)
				if(res == "新增成功"){
					ElMessage.success({
						message:"新增成功"
					})
				}else{
					ElMessage.error({
						message:"添加失败"
					})
				}
				getclassList()
				//window.location.reload()
			}
			
		})
	}
	const cancel=()=>{
		dialogFormVisible.value = false
		getclassList()
	}
	
	
	//删除商品分类
	let dialogVisible = ref(false)
	const del =async (data)=>{
		// console.log(data.separateId)
		dialogVisible.value = true
		sessionStorage.setItem("separateId",data.separateId)
	}
	
	//点击删除中的确定
	const define =async ()=>{
		dialogVisible.value = false
		//调取删除接口
		let res = await DelGoodsClass({
			separateId:sessionStorage.getItem("separateId")
		})
		// console.log("删除",res)
		if(res == "删除成功"){
			ElMessage.success({
				message:"删除成功"
			})
		}else{
			ElMessage.error({
				message:"删除失败"
			})
		}
		getclassList()
	}
	
	//获取上级分类
	let obj =ref([])
	const SuperiorSort =async ()=>{
		let res1= await CategoryParent()
		// console.log("上级分类",res1)
		
		obj.value = res1;
		// console.log("obj",obj.value)
	}
	//点击分页器
	const changePage=(page)=>{
		// console.log(page)
		pageIndex.value=page;
		getclassList()
	}
	onMounted(()=>{
		getclassList()
		SuperiorSort()
	})
</script>

<style scoped lang="less">
	.common-layout{
		background: #f2f3f5;
		.el-header{
			padding:0 !important;
			height: 10vh;
		}
		.el-main{
			height: 86vh;
			width: 98%;
			background: #fff;
			margin: 10px auto;
			.top{
				display: flex;
				justify-content: space-between;
				margin-bottom: 20px;
			}
			// :deep(.el-table .el-table__cell){
			// 	text-align: center !important;
			// }
		}
	}
	.avatarimg{
		width: 130px;
	}
	.el-table-column span{
		display: inline-block;
		color:#8079c3;
		width: 80px;
	}
	.el-input{
		width: 200px;
	}
	.el-form{
		margin-left: 50px;
	}
	.mya{
		display: inline-block;
		color: #4b5db9;
		width: 50px;
		text-align: center;
	}
	.icon{
		color: #eca146;
	}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}
</style>